package com.hehe.boot.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hehe.boot.mapper.DrugMapper;
import com.hehe.boot.pojo.Drug;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service
public class DrugService extends ServiceImpl<DrugMapper, Drug> {

    @Autowired
    private RedisTemplate redisTemplate;

    public List<Drug> getDrugLike(String query) {
        QueryWrapper<Drug> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", query);

        return this.list(queryWrapper);
    }

    public IPage<Drug> getProPage(int currentPage){
        // 构造分页条件
        Page<Drug> page = new Page<>(currentPage, 10);

        // 执行分页查询
        return this.page(page);
    }

    public IPage<Drug> getProPageLike(String query,int currentPage) {
        // 构造分页条件
        Page<Drug> page = new Page<>(currentPage, 10);

        // 构造查询条件
        QueryWrapper<Drug> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", query);

        // 执行分页查询
        return page(page, queryWrapper);
    }

    public Boolean insertDrug(Drug drug) {
        drug.setId(0L);
        return this.save(drug);
    }

    public Boolean updateDrug(Drug drug) {
        boolean result = this.updateById(drug);
        return result;
    }

    public Boolean deleteDrug(Drug drug) {
        boolean result = this.removeById(drug.getId());
        return result;
    }

    public Set<Drug> listFromRedis() {
        Set<Drug> drugs = redisTemplate.opsForSet().members("drugs");
        return drugs;
    }

    public Boolean redisRefill() {
        try {
            redisTemplate.delete("drugs");
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Drug> list = this.list();
        for(Drug item : list){
            redisTemplate.opsForSet().add("drugs",item);
        }
        return true;
    }
}
